package com.liuhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuhouse.constants.SystemCanstants;
import com.liuhouse.dto.RoleStatusDto;
import com.liuhouse.pojo.Role;
import com.liuhouse.mapper.RoleMapper;
import com.liuhouse.pojo.RoleMenu;
import com.liuhouse.service.IRoleMenuService;
import com.liuhouse.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuhouse.utils.ResponseResult;
import com.liuhouse.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author liuhouse
 * @since 2024-01-27
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IRoleMenuService roleMenuService;

    //查询用户的角色信息
    @Override
    public List<String> selectRoleKeyByUserId(Long id) {
        //判断是否是管理员,如果是,就返回集合中的角色信息中只需要admin就可以了
        if(id == 1L){
            List<String> roleKeys = new ArrayList<>();
            roleKeys.add("admin");
            return roleKeys;
        }

        //否则就查询对应普通用户所具有的角色信息
        List<String> otherRole = getBaseMapper().selectRoleKeyByOtherUserId(id);
        return otherRole;
    }

    //查询角色列表分页
    @Override
    public ResponseResult<PageVo> selectRolePage(Role role, Integer pageNum, Integer pageSize) {
        //1.构建查询条件
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        //根据角色名称进行模糊查询
        queryWrapper.like(StringUtils.hasText(role.getRoleName()) , Role::getRoleName , role.getRoleName());
        //根据状态进行查询
        queryWrapper.eq(StringUtils.hasText(role.getStatus()) , Role::getStatus , role.getStatus());
        //对校色信息进行排序
        queryWrapper.orderByAsc(Role::getRoleSort);

        //进行分页设置
        Page<Role> rolePage = new Page<>();
        //当前是第几页
        rolePage.setCurrent(pageNum);
        //每页显示的数量
        rolePage.setSize(pageSize);
        //进行分页数据的查询
        this.page(rolePage , queryWrapper);
        //转换成分页的Vo
        PageVo pageVo = new PageVo();
        pageVo.setTotal(rolePage.getTotal());
        pageVo.setRows(rolePage.getRecords());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public void changeStatus(RoleStatusDto roleStatusDto) {
        Role role = new Role();
        role.setId(roleStatusDto.getRoleId());
        role.setStatus(roleStatusDto.getStatus());
        System.out.println(role);
        this.updateById(role);
    }


    /**
     * 新增角色
     * 这里需要注意的是
     * 新增角色之后 还需要添加角色对应的权限
     * @param role
     */
    @Override
    @Transactional
    public void insertRole(Role role) {
        //添加角色
        save(role);
        //使用mybatisPlus可以自动获取自增的id值
        System.out.println(role.getId());
        //进行权限的添加[如果选择了菜单[权限] 并且菜单的数量是大于0的]
        if(role.getMenuIds() != null && role.getMenuIds().length > 0){
            insertRoleMenu(role);
        }

    }

    //修改角色信息
    @Transactional
    @Override
    public void updateRole(Role role) {
        //更新角色信息
        updateById(role);
        //删除角色对应的菜单权限
        roleMenuService.deleteRoleMenuByRoleId(role.getId());
        //添加角色和菜单权限的关系
        insertRoleMenu(role);
    }


    //查询所有角色
    @Override
    public List<Role> selectRoleAll() {
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(Role::getStatus , SystemCanstants.NORMAL);
        List<Role> list = list(roleLambdaQueryWrapper);
        return list;
    }

    @Override
    public List<Long> selectRoleIdByUserId(Long userId) {
        return getBaseMapper().selectRoleIdByUserId(userId);
    }


    //给角色添加权限
    private void insertRoleMenu(Role role) {
        //将权限列表【数组】 转化为流
        List<RoleMenu> roleMenuList = Arrays.stream(role.getMenuIds())
                .map(menuId -> new RoleMenu(role.getId(), menuId))
                .collect(Collectors.toList());
        roleMenuService.saveBatch(roleMenuList);
    }
}
